﻿using Cemit.PolyProto;
using Cemit.Awaiter;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Cemit.NetFramework
{
    [System.Obsolete("使用LobbyClient类")]
    public class PolyLobby
    {
        private const string CONFIRM_MATCH_TAG = "confirm match";

        private readonly PolySocket m_LobbySocket;
        private readonly string m_PlayerName;

        public PolyLobby(PolySocket lobbySocket, string playerName)
        {
            m_LobbySocket = lobbySocket;
            m_PlayerName = playerName;
        }

        public PolyLobby JoinMatch(Action onMatchComplete, short peopleNumber)
        {
            m_LobbySocket
                .Send(new Msg_Lobby_JoinMatch() { FullNumber = peopleNumber })
                .SetConfirmCallback(CONFIRM_MATCH_TAG, onMatchComplete);
                //.SendConfirm(CONFIRM_MATCH_TAG)

            return this;
        }

        /// <summary>可等待的方法，确认匹配，取得匹配结果</summary>
        public AsyncAction<MatchResultData> ConfirmMatch()
        {
            var action = new AsyncAction<MatchResultData>();

            m_LobbySocket.SendConfirm(CONFIRM_MATCH_TAG)
                .AddCallback<Msg_Lobby_MatchResult>(OnCallback);

            void OnCallback(Msg_Lobby_MatchResult msg)
            {
                PolyGameRoom gameRoom = null;

                if (msg.MathResult == MatchResult.Successful)
                {
                    gameRoom = new PolyGameRoom(msg.GameRoomInfo, m_PlayerName);
                }

                action.ReportResult(new MatchResultData
                {
                    matchResult = msg.MathResult,
                    room = gameRoom
                }, PolyNetwork.MonoHandle.Invoke);
            }

            return action;
        }

        public struct MatchResultData
        {
            public MatchResult matchResult;
            public PolyGameRoom room;
        }
    }
}
